package com.dianzhihan.net_demo.tcp;

import com.dianzhihan.net_demo.util.Log;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class FixedOnceClient {
    public static void main(String[] args) throws Exception {
        // 直接创建 Socket，使用服务器 IP + PORT
        Log.println("准备创建 socket(TCP 连接)");
        Socket socket = new Socket("127.0.0.1", TranslateServerShortConnection.PORT);
        Log.println("socket(TCP 连接) 创建成功");

        // 发送请求
        String engWord = "apple";
        Log.println("英文: " + engWord);
        String request = engWord + "\r\n";

        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8");
        PrintWriter writer = new PrintWriter(osWriter);

        Log.println("发送请求中");
        writer.print(request);
        writer.flush();
        Log.println("请求发送成功");

        // 等待接受响应
        InputStream is = socket.getInputStream();
        Scanner socketScanner = new Scanner(is, "UTF-8");
        // 由于我们的响应一定是一行，所以使用 nextLine() 进行读取即可
        // nextLine() 返回的数据中，会自动把 \r\n 去掉
        // TODO: 没有做 hasNextLine() 的判断
        Log.println("准备读取响应");
        String chiWord = socketScanner.nextLine();
        Log.println("中文: " + chiWord);

        socket.close();
    }
}
